package Exchanger_15;

import java.util.concurrent.Exchanger;

public class 双向数据传输测试 {
    public static void main(String[] args) {
        final Exchanger<String> exchanger = new Exchanger<String>();
        final int THREAD_PAIRS = 3;
        final int EXCHANGE_ROUNDS = 2;

        for (int i = 0; i < THREAD_PAIRS; i++) {
            final int pairId = i;

            // 线程1
            new Thread(new Runnable() {
                public void run() {
                    try {
                        for (int round = 0; round < EXCHANGE_ROUNDS; round++) {
                            String outData = "Pair" + pairId + "-Thread1-Round" + round;
                            System.out.println("线程1-" + pairId + " 发送: " + outData);
                            Thread.sleep((long)(Math.random() * 400));

                            String inData = exchanger.exchange(outData);
                            System.out.println("线程1-" + pairId + " 收到: " + inData);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "Thread1-" + i).start();

            // 线程2
            new Thread(new Runnable() {
                public void run() {
                    try {
                        for (int round = 0; round < EXCHANGE_ROUNDS; round++) {
                            String outData = "Pair" + pairId + "-Thread2-Round" + round;
                            System.out.println("线程2-" + pairId + " 发送: " + outData);
                            Thread.sleep((long)(Math.random() * 600));

                            String inData = exchanger.exchange(outData);
                            System.out.println("线程2-" + pairId + " 收到: " + inData);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "Thread2-" + i).start();
        }
    }
}